﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SocketIOClient;
using SocketIO.Serializer.NewtonsoftJson;
using SocketIOClient.Newtonsoft.Json;
using System.Threading;
using System.Diagnostics;
using SwParaPlatform2.logger;

namespace SwParaPlatform2.server
{
    class HttpRequest
    {
        private static string apiUrl = "http://43.136.94.22:13117/py/ai_para/api/model";
        private static string apiUrl_search = "http://43.136.94.22:13117/py/ai_search/api/search";
        private static SocketIOClient.SocketIO socket;

        private static string pollUrl = "http://43.136.94.22:13117/py/ai_para/poll";
        private static string pollUrl_search = "http://43.136.94.22:13117/py/ai_search/pollsearch";
        private static string userId = GetClientId();
        private static string requestid = "";
        private static string conversationid = "";

        private static bool polling = false;
        private static CancellationTokenSource cts;
        private static readonly HttpClient httpClient = new HttpClient();

        public static event Action<Dictionary<string, object>> OnDataReceived;
        public static event Action<Dictionary<string, object>> OnDataReceived2;
        public static event Action OnStopPolling;


        // ✅ 主函数：连接 Socket.IO + 可选 HTTP 请求
        public static async Task Run(string Question, Dictionary<string, Dictionary<string, object>> paramDict, string conversatioid)
        {
            requestid = GetRequestId();
            conversationid = conversatioid;

            var data = new
            {
                sQuestion = Question,
                param_dict = paramDict,
                user_id = userId,
                conversation_id = conversatioid,
                request_id = requestid
            };

            //await ConnectWebSocket(wsUrl);

            // ❗测试 HTTP polling，不推荐同时使用
            await SendHttpRequest(apiUrl, data);
            StartPolling(pollUrl, "DRIVE");
        }

        public static async Task Run2(string Question, List<string> paramList, string conversatioid)
        {
            requestid = GetRequestId();
            conversationid = conversatioid;

            var data = new
            {
                sQuestion = Question,
                param_list = paramList,
                user_id = userId,
                conversation_id = conversatioid,
                request_id = requestid
            };

            //await ConnectWebSocket(wsUrl);

            // ❗测试 HTTP polling，不推荐同时使用
            await SendHttpRequest(apiUrl_search, data);
            StartPolling(pollUrl_search, "SEARCH");
        }

        // ✅ 轮询接口：由外部调用
        public static void StartPolling(string url, string PollType)
        {
            if (polling) return;

            polling = true;
            cts = new CancellationTokenSource();
            DateTime startTime = DateTime.Now;
            Logger.Instance.Log("🔁 已开启轮询");

            Task.Run(async () =>
            {
                while (!cts.Token.IsCancellationRequested)
                {
                    var payload = new { 
                        user_id = userId,
                        conversation_id = conversationid,
                        request_id = requestid,
                    };
                    string json = JsonConvert.SerializeObject(payload);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    try
                    {
                        var response = await httpClient.PostAsync(url, content);
                        string result = await response.Content.ReadAsStringAsync();

                        var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
                        Logger.Instance.Log("📩 收到数据: " + result);

                        if (data != null && data.ContainsKey("LastMsg") && (bool)data["LastMsg"] == true)
                        {
                            Logger.Instance.Log("✅ 收到 LastMsg=true，自动停止轮询");
                            StopPolling();
                            if(PollType == "DRIVE")
                            {
                                OnDataReceived?.Invoke(data);
                            }
                            else if (PollType == "SEARCH")
                            {
                                OnDataReceived2?.Invoke(data);
                            }
                            //OnDataReceived?.Invoke(data);
                            break;
                        }

                        // 检查轮询是否已超过 60 秒
                        if ((DateTime.Now - startTime).TotalSeconds > 60)
                        {
                            Logger.Instance.Log("⏰ 轮询已持续 60 秒，自动停止");
                            var timeoutdata = new Dictionary<string, object> { ["Fail"] = true };
                            if(PollType == "DRIVE")
                            {
                                OnDataReceived?.Invoke(timeoutdata);
                            }
                            else if (PollType == "SEARCH")
                            {
                                OnDataReceived2?.Invoke(timeoutdata);
                            }
                            //OnDataReceived?.Invoke(timeoutdata);
                            StopPolling();
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Log("❌ 请求异常: " + ex.Message);
                        Logger.Instance.Log("❌ 请求异常StackTrace: " + ex.StackTrace);
                    }

                    await Task.Delay(2000);
                }
            }, cts.Token);
        }

        // ✅ 停止轮询
        public static void StopPolling()
        {
            if (!polling) return;

            cts.Cancel();
            polling = false;
            OnStopPolling.Invoke();
            Logger.Instance.Log("⏹️ 已关闭轮询");
        }

        // ✅ 构造唯一标识：IP + 主机名
        private static string GetClientId()
        {
            string ip = "UNKNOWN_IP";
            try
            {
                var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
                foreach (var addr in host.AddressList)
                {
                    if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ip = addr.ToString();
                        break;
                    }
                }
            }
            catch { }

            string hostname = Environment.MachineName;
            return $"{ip}_{hostname}";
        }

        // ✅ 构造问题唯一标识：时间戳
        private static string GetRequestId()
        {
            long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            return $"{timestamp}_RequestId";
        }

        // ✅ HTTP 请求（备用）
        static async Task SendHttpRequest(string url, object data)
        {
            using (HttpClient client = new HttpClient())
            {
                string json = JsonConvert.SerializeObject(data);
                StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
                    string responseString = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        Logger.Instance.Log("📨 [C#] 接口响应: " + responseString);
                    }
                    else
                    {
                        Logger.Instance.Log($"❌ [C#] 请求失败: {response.StatusCode} - {responseString}");
                    }
                }
                catch (Exception ex)
                {
                    Logger.Instance.Log("❌ [C#] HTTP 错误: " + ex.Message);
                }
            }
        }
    }
}
